const { findUserOfUsername, findUserOfMobile, register, editUser, getAllUser, getUserList, findUser, delUser, findUserOfId, updateAvatar } = require("../models/userModel")
// 导入joi校验包
const Joi = require("joi");
// 导入加密方法
const { cryptoPassword } = require("../utils/encryptions")
// 导入获取token方法
const { getToken } = require("../utils/getToken")

module.exports = {
  // 注册
  register: async (ctx) => {
    let { username, password, email, mobile, role_id } = ctx.request.body;

    // 参数校验 是否合法   不合法返回提示信息  并return 退出
    const schema = Joi.object({
      username: Joi.string().min(1).max(20).required(),
      password: Joi.string().pattern(/^[a-zA-Z0-9]{6,20}$/),
      repeat_password: Joi.ref('password'),
      email: Joi.string().pattern(/^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/),
      mobile: Joi.string().pattern(/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/)
    });
    const verify = schema.validate({ username, password, email, mobile });

    // 如果校验不通过 return
    if (verify.error) {
      ctx.body = {
        status: 205,
        msg: verify.error.details[0].message
      }
      return;
    }

    // 通过用户名获取用户
    let user = await findUserOfUsername(username);
    // 如果查询到用户表示已经注册
    if (user[0]) {
      ctx.body = {
        status: 205,
        msg: "此用户已注册"
      }
      return;
    }

    // 通过手机号获取用户
    let usermobile = await findUserOfMobile(mobile)
    // 如果查询到用户表示手机号码已经绑定
    if (usermobile[0]) {
      ctx.body = {
        status: 205,
        msg: "此手机号已经绑定"
      }
      return;
    }

    // 调用注册sql方法
    register(username, cryptoPassword(password), email, mobile, role_id)

    ctx.body = {
      status: 200,
      msg: "注册成功"
    }
  },
  // 登录
  login: async (ctx) => {
    const { username, password } = ctx.request.body;

    // 查询用户是否存在
    let res = await findUserOfUsername(username);
    // 如果存在 判断密码是否正确
    if (res[0]) {
      if (cryptoPassword(password) !== res[0].password) {
        ctx.body = {
          status: 205,
          msg: "您的密码错误"
        }
        return;
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "用户不存在"
      }
      return;
    }

    // 登录成功
    ctx.body = {
      status: 200,
      msg: "登录成功",
      data: res[0],
      token: getToken({ username, password })
    }
  },
  // 编辑用户
  edit: async (ctx) => {
    let { user_id, username, password, email, mobile, role_id, status } = ctx.request.body;

    // 编辑用户
    let res = await editUser(user_id, username, password, email, mobile, role_id, status);
    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "编辑成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "编辑失败"
      }
    }
  },
  // 获取用户列表
  getUserList: async (ctx) => {
    // 默认值
    let current = 1;
    let pageSize = 10;
    // 如果传了current参数就重新赋值
    if (ctx.request.query.current) {
      current = parseInt(ctx.request.query.current)
    }
    // 如果传了pageSize参数就重新赋值
    if (ctx.request.query.pageSize) {
      pageSize = parseInt(ctx.request.query.pageSize)
    }

    // 获取全部用户
    let all = await getAllUser();

    // 获取用户列表数据
    let res = await getUserList(current, pageSize)

    if (res.length !== 0) {
      ctx.body = {
        status: 200,
        msg: "获取成功",
        data: res,
        total: all.length
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "暂无用户",
        data: [],
        total: 0,
        current: current,
        pages: current - 1
      }
    }
  },
  // 查询用户
  findUser: async (ctx) => {
    const { username, mobile } = ctx.request.query;

    // 查询用户
    let res = await findUser(username, mobile);

    if (res.length === 0) {
      return ctx.body = {
        status: 205,
        msg: "没有此用户",
        data: []
      }
    }
    ctx.body = {
      status: 200,
      msg: "查询成功",
      data: res
    }
  },
  // 删除用户
  delUser: async (ctx) => {
    const { id } = ctx.request.body;

    // 删除用户
    let res = await delUser(id);

    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "删除成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "删除失败"
      }
    }
  },
  // 编辑用户回显
  editEcho: async (ctx) => {
    const { id } = ctx.request.query;

    // 查找用户
    let res = await findUserOfId(id);

    if (res.length === 0) {
      return ctx.body = {
        status: 205,
        msg: "用户不存在"
      }
    }
    ctx.body = {
      status: 200,
      msg: "查询成功",
      data: res
    }
  },
  // 修改头像
  updateAvatar: async (ctx) => {
    const { id, avatar } = ctx.request.body;
    // 修改头像
    let res = await updateAvatar(id, avatar);

    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "修改成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "修改失败"
      }
    }
  }
}